package com.sxm.yiwei.activitis;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.BillAdapter;
import com.sxm.yiwei.tools.CallPhone;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;

public class BillPickupActivity extends BaseActivity implements View.OnClickListener {

    private PullToRefreshListView pickuplist;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private ArrayList<HashMap<String, String>>  list = new ArrayList<HashMap<String, String>>();;
    private HashMap<String, String> map;
    private final static int TYPE = 2003;
    private BillAdapter billAdapter;
    private ImageView pickback;
    private ImageView nodata;
    private ImageView backmain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bill_pickup);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        initPickupView();
        getListData();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        list.clear();
        getListData();
    }

    private void getListData() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url + InternetAddressUtis.SEND_BOOKLIST);
        params.addHeader("Content-Type", "application/json");
        params.addHeader("token", token);
        params.addHeader("appId", appId);
        params.addHeader("userId", userId);
        JSONObject j = new JSONObject();
        j.put("status", "3");
        params.addParameter("params", j.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

               getData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ErrType.errType(BillPickupActivity.this,ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void getData(String result) {

        JSONObject obj = JSON.parseObject(result);
        String data = obj.getString("data");

        JSONArray array = JSONArray.parseArray(data);

        if (array.size()==0){

        }else {
            nodata.setVisibility(View.GONE);

            for (int i = 0; i < array.size(); i++) {
                map = new HashMap<>();
                JSONObject obj1 = JSON.parseObject(String.valueOf(array.get(i)));
                String consignorAddr = obj1.getString("consignorAddr");
                String id = obj1.getString("id");
                String intro = obj1.getString("intro");
                String introImage = obj1.getString("introImage");
                String orderCode = obj1.getString("orderCode");
                String totalAmount = obj1.getString("totalAmount");
                String publishTime = obj1.getString("publishTime");
                String courierMobile; courierMobile = obj1.getString("courierMobile");
                String type = obj1.getString("type");
                map.put("consignorAddr", consignorAddr);
                map.put("courierMobile", courierMobile);
                map.put("id", id);
                map.put("intro", intro);
                map.put("introImage", introImage);
                map.put("orderCode", orderCode);
                map.put("totalAmount", totalAmount);
                map.put("publishTime", publishTime);
                map.put("type", type);
                list.add(map);

            }
        }


        billAdapter = new BillAdapter(BillPickupActivity.this, list, TYPE);
        pickuplist.setAdapter(billAdapter);
        billAdapter.setOnClick(new BillAdapter.Callback() {
            @Override
            public void onclick(int v) {
                // 联系一喂员
                HashMap<String, String> map1 = (HashMap<String, String>) billAdapter.getItem(v);
                final String courierMobile = map1.get("courierMobile");
                CallPhone.callPhone(BillPickupActivity.this, courierMobile);
            }

            @Override
            public void onclick1(int v) {
                HashMap<String,String> map1 = (HashMap<String, String>) billAdapter.getItem(v);
                String id1 = map1.get("id");
                String type = map1.get("type");
                Intent i = null;
                if (type.equals("1")){
                    i = new Intent(BillPickupActivity.this,BookContentOnceActivity.class);
                }else if (type.equals("2")){
                    i = new Intent(BillPickupActivity.this,BookContentHotActivity.class);
                }else {
                    i = new Intent(BillPickupActivity.this,BookContentHelpActivity.class);
                }
                i.putExtra("id",id1);
                i.putExtra("TYPE",TYPE);
                i.putExtra("type",type);
                startActivity(i);
            }
        });
        pickuplist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                list.clear();
                getListData();
                new FinishRefresh().execute();
            }
        });
        billAdapter.notifyDataSetChanged();
    }

    private void initPickupView() {
        pickuplist = (PullToRefreshListView) findViewById(R.id.pickuplist);
        pickback = (ImageView) findViewById(R.id.billpick_back);
        nodata = (ImageView) findViewById(R.id.billpick_nodata);
        backmain = (ImageView) findViewById(R.id.billpickup_backmain);
        backmain.setOnClickListener(this);
        pickback.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.billpick_back:
                finish();
                break;
            case R.id.billpickup_backmain:
                startActivity(new Intent(BillPickupActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }


    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            billAdapter.notifyDataSetChanged();
            pickuplist.onRefreshComplete();
        }
    }
}
